﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.IO;

namespace testy {
	/// <summary>
	/// klasa testu
	/// </summary>
	public class Test {
		protected string title;
		protected uint time;
		protected List<Question> questions;
		public Test () {
			this.questions = new List<Question>();
			this.title = "";
			this.time = 0;
		}
		public Test (string fileName) : this() {
			try {
				XmlDocument doc = new XmlDocument();
				doc.Load(fileName);
				XmlElement test = (XmlElement) doc.GetElementsByTagName("test")[0];
				uint.TryParse(test.GetAttribute("time"), out this.time);
				this.title = test.GetElementsByTagName("title")[0].InnerText;
				XmlNodeList questions = test.GetElementsByTagName("question");
				foreach (XmlNode i in questions) {
					this.questions.Add(new Question(i));
				}
			} catch (Exception) {
				throw new XmlReadException();
			}
		}
		public Test (string title, List<Question> qs, uint time = 0) {
			this.title = title;
			this.questions = qs;
			this.time = time;
		}
		public void saveToFile (string fileName) {
			try {
				string output = this.generateXML();
				File.WriteAllText(fileName, output);
			} catch (Exception) {
				throw new XmlWriteException();
			}
		}
		public string generateXML () {
			string output = "";
			output += "<test time=\"" + this.time + "\"><title>" + this.title + "</title>";
			foreach (Question q in this.questions) {
				output += q.generateXML();
			}
			output += "</test>";
			return output;
		}
		public List<Question> Questions {
			get {
				return this.questions;
			}
			set {
				this.questions = value;
			}
		}
		public string Title {
			get { return this.title;}
			set {this.title = value;}
		}
		public uint Time {
			get { return this.time;}
			set { this.time = value; }
		}
	}
}
